﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Admin.Models.ConfigManager;
using Zocono.WCS.Admin.Models.User;
using Zocono.WCS.Application.AppConfigureManage;
using Zocono.WCS.Application.AppTraces;
using Zocono.WCS.Infrastructure.ApllicationDto.Enums;
using Zocono.WCS.Infrastructure.ApllicationDto.WCSTaskDto;

namespace Zocono.WCS.Admin.Controllers.ConfigManageMoudle
{
    public class RouteDetailInfoController : BaseController
    {
        private readonly RouteInfoApp _routeInfoApp;
        private readonly RouteDetailInfoApp _routeDetailInfoApp;

        public RouteDetailInfoController(RouteInfoApp routeInfoApp, RouteDetailInfoApp routeDetailInfoApp, IMemoryCache memoryCache, TracesApp tracesApp, IHttpContextAccessor httpContextAccessor) : base(memoryCache, tracesApp, httpContextAccessor)
        {
            this._routeInfoApp = routeInfoApp;
            this._routeDetailInfoApp = routeDetailInfoApp;
        }

        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 路径细节详情
        /// </summary>
        /// <returns></returns>
        public  ActionResult RouteDetailInfoAsync()
        {
            Dictionary<string, object> dropDic = EnumHelper.EnumListDic<EnumDispatchType>("", "");
            var dispatchTypes = new List<DispatchTypeSearchData>();
            if (dropDic != null)
            {
                foreach (var item in dropDic)
                {
                    dispatchTypes.Add(new DispatchTypeSearchData { ID = item.Value.ToInt32(), Desception = item.Key.ToString() });
                }
            }
            //await AddTracesInfo();
            return View(dispatchTypes);
        }

        /// <summary>
        /// 获取所有路径详情
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetAllRouteDetailInfoAsync()
        {
            var where = new QueryRouteDetailInfoDto();
            where.PageIndex = (Start / Length) + 1;
            where.PageSize = Length;
            where.FromEquipment = Request.Form["FromEquipment"].ToString();
            where.ToEquipment = Request.Form["ToEquipment"].ToString();
            where.FromStation = Request.Form["FromStation"].ToString();
            where.ToStation = Request.Form["ToStation"].ToString();
            where.FromCargo = Request.Form["FromCargo"].ToString();
            where.ToCargo = Request.Form["ToCargo"].ToString();
            var disType = Request.Form["DispatchType"].ToInt32();
            if (disType >= 0)
            {
                where.DispatchType = disType;
            }

            var routeDetails = await _routeDetailInfoApp.GetPagedRouteDetailInfoAsync(where);
            var routeDetailPages = new List<RouteDetailInfoPageData>();
            if (routeDetails != null && routeDetails.Result != null && routeDetails.Result.Count > 0)
            {
                foreach (var item in routeDetails.Result)
                {
                    routeDetailPages.Add(new RouteDetailInfoPageData()
                    {
                        ID = item.ID,
                        PrevionsID = item.PrevionsID,
                        RouteID = item.RouteID,
                        FromEquipment = item.FromEquipment,
                        ToEquipment = item.ToEquipment, 
                        FromStation = item.FromStation,
                        ToStation = item.ToStation,
                        FromCargo = item.FromCargo,
                        ToCargo = item.ToCargo,
                        FromCargoColumn = item.FromCargoColumn,
                        IsStart = item.IsStart,
                        IsEnd = item.IsEnd,
                        DispatchType = item.DispatchType,
                    }) ;
                }
            }

            var pageData = new TableData<RouteDetailInfoPageData>(Draw, routeDetails.Total, routeDetails.Total, routeDetailPages);
            //await AddTracesInfo(5, 0, "获取路径细节详情列表");
            return Json(pageData);
        }

        /// <summary>
        /// 添加或者编辑界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> RouteDetailInfoAddOrEditAsync(long id)
        {
            var routeDetail = new RouteDetailInfoPageData();

            //获取所有路径配置用于下拉选择
            var routeInfos = await _routeInfoApp.GetRouteInfoListAsync();
            routeDetail.RouteInfos = new List<RouteInfoSearchData>();
            if (routeInfos != null && routeInfos.Count > 0)
            {
                foreach (var item in routeInfos)
                {
                    routeDetail.RouteInfos.Add(new RouteInfoSearchData()
                    {
                        ID = item.ID.ToString(),
                        FromStation = item.FromStation,
                        ToStation = item.ToStation,
                    });
                }
            }
            //调度类型下拉选择
            Dictionary<string, object> dropDic = EnumHelper.EnumListDic<EnumDispatchType>("", "");
            routeDetail.DispatchTypes = new List<DispatchTypeSearchData>();
            if (dropDic != null)
            {
                foreach (var item in dropDic)
                {
                    routeDetail.DispatchTypes.Add(new DispatchTypeSearchData { ID = item.Value.ToInt32(), Desception = item.Key.ToString() });
                }
            }
            if (id > 0)
            {
                var routeDetailInfo = await _routeDetailInfoApp.GetRouteDetailInfoByIdAsync(id);
                if (routeDetailInfo != null)
                {
                    routeDetail.ID = routeDetailInfo.ID;
                    routeDetail.PrevionsID = routeDetailInfo.PrevionsID;
                    routeDetail.RouteID = routeDetailInfo.RouteID;
                    routeDetail.FromEquipment = routeDetailInfo.FromEquipment;
                    routeDetail.ToEquipment = routeDetailInfo.ToEquipment;
                    routeDetail.FromCargo = routeDetailInfo.FromCargo;
                    routeDetail.ToCargo = routeDetailInfo.ToCargo;
                    routeDetail.DispatchType = routeDetailInfo.DispatchType;
                    routeDetail.IsStart = routeDetailInfo.IsStart;
                    routeDetail.IsEnd = routeDetailInfo.IsEnd;
                    routeDetail.FromCargoColumn = routeDetailInfo.FromCargoColumn;
                }
            }
            return View(routeDetail);
        }

        /// <summary>
        /// 通过路径ID获取所有路径细节详情  用于下拉数据
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetRouteDetailInfoByRouteIdAsync()
        {
            var routeId = Request.Form["routeID"].ToInt64();
            var routeDetails = await _routeDetailInfoApp.GetRouteDetailInfoByRouteIDAsync(routeId);
            var routeSDto = new List<RouteDetailInfoSearchData>();
            if (routeDetails != null && routeDetails.Count > 0)
            {
                foreach (var item in routeDetails)
                {
                    routeSDto.Add(new RouteDetailInfoSearchData()
                    {
                        ID = item.ID,
                        ToEquipment = item.ToEquipment,
                        ToCargo = item.ToCargo
                    });
                }
            }
            return Json(routeSDto);
        }


        public async Task<JsonResult> OperateRouteDetailInfoAsync()
        {
            var routeDetailInfoDto = new RouteDetailInfoDto();
            routeDetailInfoDto.ID = Request.Form["id"].ToInt64();
            routeDetailInfoDto.PrevionsID = Request.Form["PrevionsID"].ToInt64();
            routeDetailInfoDto.RouteID = Request.Form["RouteID"].ToInt64();
            routeDetailInfoDto.DispatchType = (EnumDispatchType)Enum.Parse(typeof(EnumDispatchType), Request.Form["DispatchType"].ToString());
            routeDetailInfoDto.IsStart = Request.Form["IsStart"].ToBool();
            routeDetailInfoDto.IsEnd = Request.Form["IsEnd"].ToBool();
            routeDetailInfoDto.FromEquipment = Request.Form["FromEquipment"].ToString();
            routeDetailInfoDto.FromCargo = Request.Form["FromCargo"].ToString();
            routeDetailInfoDto.FromCargoColumn = Request.Form["FromCargoColumn"].ToString();
            routeDetailInfoDto.ToEquipment = Request.Form["ToEquipment"].ToString();
            routeDetailInfoDto.ToCargo = Request.Form["ToCargo"].ToString();

            bool result;
            string msg;
            try
            {
                if (routeDetailInfoDto.ID == 0)
                {
                    result = await _routeDetailInfoApp.CreateRouteDetailInfoAsync(routeDetailInfoDto);
                    await AddTracesInfo(2, 0, "新增路径详情配置");
                }
                else
                {
                    result = await _routeDetailInfoApp.ModifyRouteDetailInfoAsync(routeDetailInfoDto);
                    await AddTracesInfo(3, 0, "修改路径详情配置");
                }
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }

            return CreateJsonGetResult(result, msg);
        }

        /// <summary>
        /// 根据id删除数据
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> DeleteRouteDetailInfoAsync()
        {
            var id = Request.Form["id"].ToInt64();
            bool result;
            string msg;
            try
            {
                result = await _routeDetailInfoApp.DeleteRouteDetailInfoByIdAsync(id);
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }
            await AddTracesInfo(4, 0, "删除路径详情配置");
            return CreateJsonGetResult(result, msg);
        }


        /// <summary>
        /// 一次性添加界面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> RouteDetailInfoAddMultiAsync(long id)
        {
            var routeDetail = new RouteDetailInfoPageData();

            //获取所有路径配置用于下拉选择
            var routeInfos = await _routeInfoApp.GetRouteInfoListAsync();
            routeDetail.RouteInfos = new List<RouteInfoSearchData>();
            if (routeInfos != null && routeInfos.Count > 0)
            {
                foreach (var item in routeInfos)
                {
                    routeDetail.RouteInfos.Add(new RouteInfoSearchData()
                    {
                        ID = item.ID.ToString(),
                        FromStation = item.FromStation,
                        ToStation = item.ToStation,
                    });
                }
            }
            //调度类型下拉选择
            Dictionary<string, object> dropDic = EnumHelper.EnumListDic<EnumDispatchType>("", "");
            routeDetail.DispatchTypes = new List<DispatchTypeSearchData>();
            if (dropDic != null)
            {
                foreach (var item in dropDic)
                {
                    routeDetail.DispatchTypes.Add(new DispatchTypeSearchData { ID = item.Value.ToInt32(), Desception = item.Key.ToString() });
                }
            }
            //if (id > 0)
            //{
            //    var routeDetailInfo = await _routeDetailInfoApp.GetRouteDetailInfoByIdAsync(id);
            //    if (routeDetailInfo != null)
            //    {
            //        routeDetail.ID = routeDetailInfo.ID;
            //        routeDetail.PrevionsID = routeDetailInfo.PrevionsID;
            //        routeDetail.RouteID = routeDetailInfo.RouteID;
            //        routeDetail.FromEquipment = routeDetailInfo.FromEquipment;
            //        routeDetail.ToEquipment = routeDetailInfo.ToEquipment;
            //        routeDetail.FromCargo = routeDetailInfo.FromCargo;
            //        routeDetail.ToCargo = routeDetailInfo.ToCargo;
            //        routeDetail.DispatchType = routeDetailInfo.DispatchType;
            //        routeDetail.IsStart = routeDetailInfo.IsStart;
            //        routeDetail.IsEnd = routeDetailInfo.IsEnd;
            //        routeDetail.FromCargoColumn = routeDetailInfo.FromCargoColumn;
            //    }
            //}
            return View(routeDetail);
        }


        /// <summary>
        /// 一次性添加
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> AddMultiRouteDetailInfoAsync()
        {
            //获取起始工位号  取查询路径id
            var FromStation = Request.Form["FromStation".ToString()];
            var ToStation = Request.Form["ToStation".ToString()];
            var routeInfo = await _routeInfoApp.GetRouteInfoByFromAndToAsync(FromStation, ToStation);

            var routeDetailInfoDto1 = new RouteDetailInfoDto();
            routeDetailInfoDto1.ID = Request.Form["id"].ToInt64();
            routeDetailInfoDto1.PrevionsID = Request.Form["PrevionsID"].ToInt64();
            routeDetailInfoDto1.RouteID = Request.Form["RouteID"].ToInt64();
            if (routeInfo != null)
            {
                routeDetailInfoDto1.RouteID = routeInfo.ID;
            }
            routeDetailInfoDto1.DispatchType = (EnumDispatchType)Enum.Parse(typeof(EnumDispatchType), Request.Form["DispatchType"].ToString());
            routeDetailInfoDto1.FromEquipment = Request.Form["FromEquipment"].ToString();
            routeDetailInfoDto1.FromCargo = Request.Form["FromCargo"].ToString();
            routeDetailInfoDto1.FromCargoColumn = Request.Form["FromCargoColumn"].ToString();
            routeDetailInfoDto1.ToEquipment = Request.Form["ToEquipment"].ToString();
            routeDetailInfoDto1.ToCargo = Request.Form["ToCargo"].ToString();

            var isOnlyOne = Request.Form["IsStart"].ToBool();

            RouteDetailInfoDto routeDetailInfoDto2 = null;
            if (isOnlyOne)
            {
                routeDetailInfoDto1.IsStart = true;
                routeDetailInfoDto1.IsEnd = true;
            }
            else
            {
                routeDetailInfoDto1.IsStart = true;
                routeDetailInfoDto1.IsEnd = false;
                //有第二段路径
                routeDetailInfoDto2 = new RouteDetailInfoDto();
                routeDetailInfoDto2.RouteID = routeDetailInfoDto1.RouteID;
                routeDetailInfoDto2.DispatchType = (EnumDispatchType)Enum.Parse(typeof(EnumDispatchType), Request.Form["DispatchType2"].ToString());
                routeDetailInfoDto2.FromEquipment = Request.Form["FromEquipment2"].ToString();
                routeDetailInfoDto2.FromCargo = Request.Form["FromCargo2"].ToString();
                routeDetailInfoDto2.FromCargoColumn = Request.Form["FromCargoColumn2"].ToString();
                routeDetailInfoDto2.ToEquipment = Request.Form["ToEquipment2"].ToString();
                routeDetailInfoDto2.ToCargo = Request.Form["ToCargo2"].ToString();
                routeDetailInfoDto2.IsStart = false;
                routeDetailInfoDto2.IsEnd = true;
            }


            bool result = false;
            string msg;
            try
            {
                
                 var lastId = await _routeDetailInfoApp.CreateRouteDetailInfoOutIdAsync(routeDetailInfoDto1);
                if (!isOnlyOne)
                {
                    routeDetailInfoDto2.PrevionsID = lastId;
                    result = await _routeDetailInfoApp.CreateRouteDetailInfoAsync(routeDetailInfoDto2);
                }
                else
                {
                    if (lastId > 0)
                    {
                        result = true;
                    }
                }
                await AddTracesInfo(2, 0, "新增路径详情配置");

                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }

            return CreateJsonGetResult(result, msg);
        }


    }
}
